<template>
  <div class="data-generator-container">
    <!-- 头部区域 -->
    <header class="header">
      <h1 class="title">测试数据集生成器</h1>
      <div class="header-actions">
        <el-button>
          <el-icon><User /></el-icon>
          登录
        </el-button>
        <el-button type="primary">
          <el-icon><Plus /></el-icon>
          注册
        </el-button>
      </div>
    </header>
    
    <!-- 主体内容区域 -->
    <main class="main-content">
      <!-- 左侧配置面板 (30%) -->
      <div class="config-panel">
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <span>基本配置</span>
            </div>
          </template>
          
          <div class="slider-container">
            <el-text class="slider-label">生成数据量: {{ formatNumber(dataCount) }} 条</el-text>
            <el-slider 
              v-model="dataCount" 
              :min="1000" 
              :max="1000000" 
              :step="1000"
            />
          </div>
          
          <div class="mode-selection">
            <el-text class="mode-label">生成模式</el-text>
            <el-radio-group v-model="generateMode">
              <el-radio label="online">在线生成</el-radio>
              <el-radio label="offline">离线下载</el-radio>
            </el-radio-group>
          </div>
        </el-card>
        
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <span>数据源</span>
            </div>
          </template>
          
          <div 
            class="drag-area" 
            :class="{ 'drag-active': isDragActive }"
            @dragover.prevent="handleDragOver"
            @dragleave="handleDragLeave"
            @drop.prevent="handleDrop"
            @click="triggerFileSelect"
          >
            <el-icon :size="48" class="upload-icon"><Upload /></el-icon>
            <h3>拖放SQL文件到此处或点击上传</h3>
            <p class="upload-description">支持导入.sql文件自动解析表结构</p>
            <el-button>
              <el-icon><FolderOpened /></el-icon>
              选择文件
            </el-button>
          </div>
          
          <input 
            type="file" 
            ref="fileInput" 
            style="display: none" 
            accept=".sql" 
            @change="handleFileSelect"
          />
        </el-card>
        
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <span>数据存储</span>
            </div>
          </template>
          
          <div class="storage-config">
            <div class="config-item">
              <el-text class="item-label">保存周期</el-text>
              <el-select v-model="storagePeriod">
                <el-option label="7天（免费用户）" value="7" />
                <el-option label="30天（高级会员）" value="30" />
                <el-option label="永久保存（白金会员）" value="0" />
              </el-select>
            </div>
            
            <div class="config-item">
              <el-text class="item-label">文件格式</el-text>
              <el-select v-model="fileFormat">
                <el-option label="CSV格式" value="csv" />
                <el-option label="JSON格式" value="json" />
                <el-option label="SQL格式" value="sql" />
                <el-option label="Excel格式" value="excel" />
              </el-select>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 右侧字段编辑区 (70%) -->
      <div class="field-editor">
        <h2 class="section-title">字段规则配置</h2>
        
        <el-table :data="fieldData" class="field-table" style="width: 100%">
          <el-table-column prop="name" label="字段名" />
          <el-table-column label="数据类型" width="180">
            <template #default="scope">
              <el-select v-model="scope.row.type">
                <el-option label="INTEGER" value="INTEGER" />
                <el-option label="STRING" value="STRING" />
                <el-option label="UUID" value="UUID" />
                <el-option label="BIGINT" value="BIGINT" />
                <el-option label="FLOAT" value="FLOAT" />
                <el-option label="BOOLEAN" value="BOOLEAN" />
                <el-option label="ENUM" value="ENUM" />
                <el-option label="DATE" value="DATE" />
                <el-option label="TIMESTAMP" value="TIMESTAMP" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="长度" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.length" placeholder="长度" />
            </template>
          </el-table-column>
          <el-table-column prop="constraints" label="约束" width="160" />
          <el-table-column label="规则配置" width="120">
            <template #default="scope">
              <el-button 
                @click="openRuleModal(scope.$index)" 
                circle 
                plain
              >
                <el-icon><Setting /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 规则配置模态框 -->
        <el-dialog v-model="ruleModalVisible" title="规则配置" width="500">
          <div class="rule-config">
            <div class="rule-header">
              <span class="field-name">字段: {{ currentField.name }}</span>
            </div>
            
            <div class="config-item">
              <el-text class="item-label">规则类型</el-text>
              <el-select v-model="currentRule.type" style="width: 100%">
                <el-option label="正则表达式" value="regex" />
                <el-option label="范围配置" value="range" />
                <el-option label="枚举值" value="enum" />
                <el-option label="自定义脚本" value="script" />
                <el-option label="模式生成" value="pattern" />
              </el-select>
            </div>
            
            <div class="config-item">
              <el-text class="item-label">配置选项</el-text>
              <div class="rule-options">
                <div v-if="currentRule.type === 'range'">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-input v-model="currentRule.min" placeholder="最小值">
                        <template #prepend>最小值</template>
                      </el-input>
                    </el-col>
                    <el-col :span="12">
                      <el-input v-model="currentRule.max" placeholder="最大值">
                        <template #prepend>最大值</template>
                      </el-input>
                    </el-col>
                  </el-row>
                  <div class="checkbox-group">
                    <el-checkbox v-model="currentRule.allowEmpty">允许为空值</el-checkbox>
                    <el-checkbox v-model="currentRule.unique" checked>唯一值约束</el-checkbox>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="preview-section">
              <el-text class="preview-label">预览</el-text>
              <div class="preview-content">
                <div v-if="currentRule.type === 'range'">
                  <p>值范围: <span class="preview-value">{{ currentRule.min }} ~ {{ currentRule.max }}</span></p>
                  <p>唯一值: {{ currentRule.unique ? '是' : '否' }}</p>
                  <p>空值: {{ currentRule.allowEmpty ? '允许' : '不允许' }}</p>
                </div>
              </div>
            </div>
          </div>
          
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="ruleModalVisible = false">取消</el-button>
              <el-button type="primary" @click="applyRule">应用规则</el-button>
            </span>
          </template>
        </el-dialog>
        
        <!-- 数据生成预览 -->
        <div class="preview-container" :class="{ 'preview-show': showPreview }">
          <div class="preview-header">
            <h3 class="preview-title">生成数据预览</h3>
            <el-button size="small" type="primary" @click="toggleChart">
              {{ showChart ? '隐藏图表' : '查看图表' }}
            </el-button>
          </div>
          
          <!-- 表格预览 -->
          <div v-if="!showChart" class="table-preview">
            <el-table :data="previewData" height="250" style="width: 100%">
              <el-table-column
                v-for="field in fieldData"
                :key="field.name"
                :prop="field.name"
                :label="field.name"
                :width="getColumnWidth(field.name)">
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 图表预览 -->
          <div v-show="showChart" ref="chartContainer" class="chart-container" style="height: 260px;"></div>
        </div>
      </div>
    </main>
    
    <!-- 底部操作栏 -->
    <footer class="footer">
    <el-button>
      <el-icon><Clock /></el-icon>
      历史生成记录
    </el-button>
    
    <div class="progress-section">
      <div class="progress-container">
        <el-progress :percentage="progress" :show-text="false" />
      </div>
      <span class="progress-text">{{ progressText }}</span>
    </div>
    
    <el-button type="primary" @click="generateData">
      <el-icon><Refresh /></el-icon>
      生成测试数据
    </el-button>
  </footer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { User, Plus, Upload, FolderOpened, Setting, Clock, Refresh } from '@element-plus/icons-vue'

// 响应式数据
const dataCount = ref(50000)
const generateMode = ref('online')
const storagePeriod = ref('7')
const fileFormat = ref('csv')
const isDragActive = ref(false)
const fileInput = ref(null)
const ruleModalVisible = ref(false)
const showPreview = ref(false)
const showChart = ref(false)
const progress = ref(0)
const progressText = ref('准备生成数据...')
const chartContainer = ref(null)
const previewData = ref([])

// 当前字段和规则
const currentField = reactive({
  name: '',
  index: -1
})

const currentRule = reactive({
  type: 'range',
  min: 1000,
  max: 9999,
  allowEmpty: false,
  unique: true
})

// 字段数据
const fieldData = ref([
  {
    name: '用户ID',
    type: 'BIGINT',
    length: '',
    constraints: 'PRIMARY KEY, NOT NULL'
  },
  {
    name: '姓名',
    type: 'STRING',
    length: '32',
    constraints: 'NOT NULL'
  },
  {
    name: '邮箱地址',
    type: 'STRING',
    length: '64',
    constraints: 'UNIQUE, NOT NULL'
  },
  {
    name: '用户状态',
    type: 'ENUM',
    length: '10',
    constraints: "DEFAULT 'active'"
  },
  {
    name: '注册时间',
    type: 'TIMESTAMP',
    length: '',
    constraints: 'NOT NULL'
  }
])

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString()
}

// 计算列宽
const getColumnWidth = (fieldName) => {
  // 根据字段名长度和类型计算合适的列宽
  const field = fieldData.value.find(f => f.name === fieldName);
  if (!field) return 150;
  
  // 基于字段名长度计算
  const nameLength = fieldName.length * 12;
  
  // 根据字段类型调整
  let typeWidth = 100;
  if (field.type === 'BIGINT' || field.type === 'INTEGER') {
    typeWidth = 120;
  } else if (field.type === 'STRING') {
    typeWidth = Math.max(120, field.length ? parseInt(field.length) * 8 : 150);
  } else if (field.type === 'TIMESTAMP') {
    typeWidth = 180;
  } else if (field.type === 'ENUM') {
    typeWidth = 150;
  }
  
  return Math.max(nameLength, typeWidth, 100);
}

// 拖拽事件处理
const handleDragOver = () => {
  isDragActive.value = true
}

const handleDragLeave = () => {
  isDragActive.value = false
}

const handleDrop = (e) => {
  isDragActive.value = false
  const file = e.dataTransfer.files[0]
  if (file && file.name.endsWith('.sql')) {
    handleFile(file)
  }
}

const triggerFileSelect = () => {
  fileInput.value.click()
}

const handleFileSelect = (e) => {
  const file = e.target.files[0]
  if (file && file.name.endsWith('.sql')) {
    handleFile(file)
  }
}

const handleFile = (file) => {
  // 模拟文件处理
  console.log('文件已选择:', file.name)
  // 这里可以添加实际的文件处理逻辑
}

// 规则配置
const openRuleModal = (index) => {
  currentField.name = fieldData.value[index].name
  currentField.index = index
  ruleModalVisible.value = true
}

const applyRule = () => {
  ruleModalVisible.value = false
  // 这里可以添加规则应用的逻辑
}

// 图表相关
let chartInstance = null

const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartContainer.value)
  
  const option = {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'category',
      data: ['用户ID', '姓名', '邮箱', '状态', '时间'],
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '字段分布',
        type: 'bar',
        barWidth: '45%',
        data: [
          { value: 1253, itemStyle: { color: '#409EFF' } },
          { value: 914, itemStyle: { color: '#67C23A' } },
          { value: 867, itemStyle: { color: '#E6A23C' } },
          { value: 1032, itemStyle: { color: '#909399' } },
          { value: 769, itemStyle: { color: '#F56C6C' } }
        ]
      }
    ]
  }
  
  chartInstance.setOption(option)
}

const toggleChart = () => {
  showChart.value = !showChart.value
  if (showChart.value && showPreview.value) {
    nextTick(() => {
      initChart()
    })
  }
}

// 生成预览数据
const generatePreviewData = (count = 10) => {
  const data = [];
  for (let i = 0; i < count; i++) {
    const row = {};
    fieldData.value.forEach(field => {
      // 根据字段类型生成示例数据
      switch (field.type) {
        case 'BIGINT':
          row[field.name] = Math.floor(Math.random() * 1000000) + 1000;
          break;
        case 'STRING':
          if (field.name.includes('姓名')) {
            const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
            row[field.name] = names[Math.floor(Math.random() * names.length)];
          } else if (field.name.includes('邮箱')) {
            const domains = ['example.com', 'test.com', 'demo.com'];
            row[field.name] = `user${Math.floor(Math.random() * 10000)}@${domains[Math.floor(Math.random() * domains.length)]}`;
          } else {
            row[field.name] = `${field.name}${Math.floor(Math.random() * 1000)}`;
          }
          break;
        case 'ENUM':
          if (field.name.includes('状态')) {
            const statuses = ['active', 'inactive', 'pending'];
            row[field.name] = statuses[Math.floor(Math.random() * statuses.length)];
          } else {
            row[field.name] = 'default';
          }
          break;
        case 'TIMESTAMP':
          // 生成最近30天内的随机时间
          const date = new Date();
          date.setDate(date.getDate() - Math.floor(Math.random() * 30));
          row[field.name] = date.toISOString().slice(0, 19).replace('T', ' ');
          break;
        default:
          row[field.name] = `${field.name}${Math.floor(Math.random() * 100)}`;
      }
    });
    data.push(row);
  }
  return data;
}

// 数据生成
const generateData = () => {
  progress.value = 0
  progressText.value = '开始生成数据...'
  showPreview.value = true
  showChart.value = false;
  
  // 生成预览数据
  previewData.value = generatePreviewData(10);
  
  const interval = setInterval(() => {
    progress.value += Math.random() * 5
    if (progress.value > 100) progress.value = 100
    
    if (progress.value < 30) {
      progressText.value = `准备数据源 (${Math.round(progress.value)}%)...`
    } else if (progress.value < 70) {
      progressText.value = `生成测试数据 (${Math.round(progress.value)}%)...`
    } else {
      progressText.value = `进行数据校验 (${Math.round(progress.value)}%)...`
    }
    
    if (progress.value >= 100) {
      clearInterval(interval)
      progressText.value = '数据生成完成!'
      
      // 显示预览
      if (showChart.value) {
        nextTick(() => {
          initChart()
        })
      }
    }
  }, 200)
}

// 窗口大小变化时重绘图表
onMounted(() => {
  window.addEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
})
</script>

<style scoped>
.data-generator-container {
  width: 100%;
  max-width: 1440px;
  margin: 0 auto;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 10px);
  padding: 5px;
  padding-top: 80px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding: 12px 24px;
  background: white;
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: #2A5C9A;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 按钮样式 */
.btn {
  padding: 10px 24px;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.btn-primary {
  background: #2A5C9A;
  color: white;
}

.btn-primary:hover {
  background: #1e4877;
}

.btn-gray {
  background: #f0f0f0;
  color: #555;
}

.btn-gray:hover {
  background: #e0e0e0;
}

.main-content {
  display: flex;
  flex: 1;
  height: calc(100% - 100px);
}

.config-panel {
  width: 30%;
  border-right: 1px solid #eee;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.config-card {
  border-radius: 8px;
}

.card-header {
  font-weight: 600;
  color: #606266;
}

.slider-container {
  margin: 16px 0;
}

.slider-label {
  display: block;
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

.mode-selection {
  margin-top: 16px;
}

.mode-label {
  display: block;
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

.drag-area {
  border: 2px dashed #ccc;
  padding: 24px;
  text-align: center;
  border-radius: 4px;
  margin: 12px 0;
  transition: all 0.3s;
  color: #606266;
  cursor: pointer;
}

.drag-area:hover,
.drag-active {
  border-color: #2A5C9A;
  background: #f0f7ff;
}

.upload-icon {
  margin-bottom: 8px;
  color: #606266;
}

.upload-description {
  font-size: 11px;
  color: #909399;
  margin: 6px 0 12px;
}

.storage-config {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.item-label {
  font-size: 13px;
  color: #606266;
}

.field-editor {
  width: 70%;
  padding: 16px;
  overflow: auto;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
}

.field-table :deep(.el-table__row:hover) {
  background: #f0f7ff;
}

.rule-config {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.rule-header {
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.field-name {
  font-weight: 600;
  font-size: 15px;
}

.rule-options {
  margin-top: 12px;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-top: 12px;
}

.preview-section {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
}

.preview-label {
  display: block;
  font-weight: 600;
  margin-bottom: 8px;
}

.preview-content {
  font-size: 14px;
  color: #606266;
}

.preview-value {
  font-family: monospace;
}

.preview-container {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.5s;
  margin-top: 16px;
}

.preview-show {
  max-height: 300px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.preview-title {
  font-size: 16px;
  font-weight: 600;
}

.chart-container {
  width: 100%;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-top: 1px solid #eee;
  flex-shrink: 0;
}

.progress-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 250px;
}

.progress-container {
  width: 100%;
  margin-bottom: 8px;
  background: #e0e0e0;
  height: 10px;
  border-radius: 5px;
  overflow: hidden;
}

/* 进度条样式 */
.progress-container :deep(.el-progress-bar__outer) {
  background: #e0e0e0;
  border-radius: 5px;
  overflow: hidden;
}

.progress-container :deep(.el-progress-bar__inner) {
  background: #4CAF50;
  border-radius: 5px;
}

.progress-text {
  font-size: 14px;
  color: #606266;
}
</style>